package 脚本;
import java.util.Scanner;

public class ProducerConsumerExample {
    private static final int BUFFER_SIZE = 10;
    private static String[] buffer = new String[BUFFER_SIZE];
    private static int count = 0;
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        Thread producerThread = new Thread(() -> {
            while (true) {
                if (isBufferFull()) {
                    try {
                        synchronized(ProducerConsumerExample.class) {
                            ProducerConsumerExample.class.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                String data = scanner.nextLine();
                addToBuffer(data);
                synchronized(ProducerConsumerExample.class) {
                    ProducerConsumerExample.class.notifyAll();
                }
            }
        });

        Thread consumerThread = new Thread(() -> {
            while (true) {
                if (isBufferEmpty()) {
                    try {
                        synchronized(ProducerConsumerExample.class) {
                            ProducerConsumerExample.class.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                String data = removeFromBuffer();
                System.out.println("Consumed item: " + data);
                synchronized(ProducerConsumerExample.class) {
                    ProducerConsumerExample.class.notifyAll();
                }
            }
        });

        producerThread.start();
        consumerThread.start();
    }

    private static synchronized boolean isBufferFull() {
        return count == BUFFER_SIZE;
    }

    private static synchronized boolean isBufferEmpty() {
        return count == 0;
    }

    private static synchronized void addToBuffer(String data) {
        buffer[count++] = data;
    }

    private static synchronized String removeFromBuffer() {
        String data = buffer[0];
        System.arraycopy(buffer, 1, buffer, 0, --count);
        buffer[count] = null;
        return data;
    }
}
